package StateMod;

public class code {
    // 状态接口

    interface State {

        void doSomething();
    }

// 具体状态类：Closed
    class Closed implements State {

        @Override
        public void doSomething() {
            System.out.println("Connection is closed.");
        }
    }

// 具体状态类：Established
    class Established implements State {

        @Override
        public void doSomething() {
            System.out.println("Connection is established.");
        }
    }

// 具体状态类：Listening
    class Listening implements State {

        @Override
        public void doSomething() {
            System.out.println("Connection is listening.");
        }
    }

// 上下文类：TCPConnection
    class TCPConnection {

        private State state;

        public TCPConnection() {
            this.state = new Closed(); // 默认状态
        }

        public void changeState(State state) {
            this.state = state;
        }

        public void doSomething() {
            state.doSomething();
        }

        public void response(String message) {
            // 根据不同的消息改变状态
            switch (message) {
                case "open":
                    changeState(new Established());
                    break;
                case "listen":
                    changeState(new Listening());
                    break;
                case "close":
                    changeState(new Closed());
                    break;
            }
        }
    }

}
